
from cProfile import Profile
from flask import request
import logging
import functools
import time
time_logger = logging.getLogger('time_logger')


def time_statistic(args_index: int = None, kwargs_key: str = None):
    def _decorators(fn):
        @functools.wraps(fn)
        def _wrapper(*args, **kwargs):
            start = time.time()
            key = None
            if kwargs_key is not None:
                key = kwargs.get(kwargs_key, None)
            if args_index is not None:
                try:
                    key = args[args_index]
                except IndexError:
                    pass
            if key is not None:
                time_logger.info('Start [%s] Key:%s args:%s kwargs:%s', fn.__name__, key, args, kwargs)
                res = fn(*args, **kwargs)
                time_logger.info('End [%s]  Key:%s res:%s time:%s', fn.__name__, key, res, time.time() - start)
            else:
                time_logger.info('Start [%s] args:%s kwargs:%s', fn.__name__, args, kwargs)
                res = fn(*args, **kwargs)
                time_logger.info('End [%s] res:%s time:%s', fn.__name__, res, time.time() - start)
            return res
        return _wrapper
    return _decorators


# def profile_wrapper(func):
#     @functools.wraps(func)
#     def wrapper(*args, **kwargs):
#         prof = Profile()
#         prof.enable()
#         res =func(*args, **kwargs)
#         prof.create_stats()
#         prof.print_stats()
#         prof.dump_stats('ddd')
#         return res
#     return wrapper
